package cn.xiaoming.car.server.account.service.impl;

import cn.xiaoming.car.server.account.dao.persist.repository.impl.AdminRepositoryImpl;
import cn.xiaoming.car.server.account.pojo.entity.Admin;
import cn.xiaoming.car.server.account.pojo.param.AdminAddNewParam;
import cn.xiaoming.car.server.account.pojo.vo.AdminListItemVO;
import cn.xiaoming.car.server.account.pojo.vo.AdminStandardVO;
import cn.xiaoming.car.server.account.service.IAdminService;
import cn.xiaoming.car.server.common.ex.ServiceException;
import cn.xiaoming.car.server.common.pojo.vo.PageData;
import cn.xiaoming.car.server.common.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 处理管理员数据的业务实现类
 *
 * @author java@john.cn
 * @version 1.0
 */
@Slf4j
@Service
public class AdminServiceImpl implements IAdminService {

    @Value("${xiaoming-car.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    AdminRepositoryImpl adminRepository;

    public AdminServiceImpl() {
        log.debug("创建业务类对象：AdminServiceImpl");
    }
    @Override
    public void addNew(AdminAddNewParam adminAddNewParam) {

        // 检查用户名是否被占用
        {
            String username = adminAddNewParam.getUsername();
            int count=adminRepository.countByUsername(username);
            if(count>0){
                String message = "添加管理员失败，用户名已经被占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }
        // 检查手机号是否被占用
        {
            String phone = adminAddNewParam.getPhone();
            int count = adminRepository.countByPhone(phone);
            if (count > 0) {
                String message = "添加管理员失败，手机号码已经被占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }

        // 检查邮箱是否被占用
        {
            String email = adminAddNewParam.getEmail();
            int count = adminRepository.countByEmail(email);
            if (count > 0) {
                String message = "添加管理员失败，电子邮箱已经被占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }
        Admin admin=new Admin();
        BeanUtils.copyProperties(adminAddNewParam,admin);

        int rows = adminRepository.insert(admin);
        if (rows != 1) {
            String message = "添加管理员失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除管理员】的业务，参数：{}", id);
        Object queryResult = adminRepository.getStandardById(id);
        if (queryResult == null) {
            String message = "删除管理员失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        log.debug("即将执行删除数据，参数：{}", id);
        int rows = adminRepository.deleteById(id);
        if (rows != 1) {
            String message = "删除管理员失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
    }

    @Override
    public void setEnable(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        updateEnableById(id, 0);
    }

    @Override
    public AdminStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询管理员】业务，参数：{}", id);
        AdminStandardVO currentUser = adminRepository.getStandardById(id);
        if (currentUser == null) {
            String message = "获取管理员详情失败，尝试访问的用户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return currentUser;
    }

    @Override
    public PageData<AdminListItemVO> list(Integer pageNum) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}", pageNum);
        PageData<AdminListItemVO> pageData = adminRepository.list(pageNum, defaultQueryPageSize);
        return pageData;
    }

    @Override
    public PageData<AdminListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageData<AdminListItemVO> pageData = adminRepository.list(pageNum, pageSize);
        return pageData;
    }

    private void updateEnableById(Long id, Integer enable) {
        log.debug("开始处理【{}管理员】的业务，ID：{}，目标状态：{}", ENABLE_TEXT[enable], id, enable);
        AdminStandardVO queryResult = adminRepository.getStandardById(id);
        if (queryResult == null) {
            String message = ENABLE_TEXT[enable] + "管理员失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        if (queryResult.getEnable().equals(enable)) {
            String message = ENABLE_TEXT[enable] + "管理员失败，当前用户已经处于"
                    + ENABLE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        Admin admin=new Admin();
        admin.setId(id);
        admin.setEnable(enable);
        log.debug("即将修改数据，参数：{}", admin);
        int rows = adminRepository.updateById(admin);
        if (rows != 1) {
            String message = ENABLE_TEXT[enable] + "管理员失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

}
